﻿const pool = require("../base/mysql").pool,
	staticPath = require('../config-local').staticPath,
	userService = require('../user/userService'),
	moment = require('moment');
//=====================SQL语句===========================//
const sql_createCoursesetList = "insert into courseset_local(userId,createTime,lastUpdateTime) values (?,?,?)",
	sql_getCoursesetList = "SELECT `id`,`coursesetName`,UNIX_TIMESTAMP(`createTime`) as createTime,UNIX_TIMESTAMP(`lastUpdateTime`) as lastUpdateTime,publishedFlag FROM `courseset_local` where userId=? order by id",
	sql_getCoursesetContent = "select * from courseset_local where  id=?",
	sql_getReleaseCoursesetContent = "select * from courseset_release where  coursesetId=?",
	sql_getSuccessCoursesetContent = "select * from courseset_success where  coursesetId=?",
	sql_coursesetNameSave = "update courseset_local set coursesetName=?,lastUpdateTime=? where userId=? and id=?",
	sql_delCoursesetList = "delete from course_list_local where userId=? and coursesetId=?",
	sql_delCourseset = "delete from courseset_local where userId=? and id=?",
	sql_delCoursesetSection = "delete from course_local where userId=? and coursesetId=?",
	sql_createCourseList = "insert into course_list_local(userId,coursesetId) values (?,?)",
	sql_getOrderNum = "select count(id) as orderNum from course_list_local where userId=? and coursesetId=?",
	sql_updateOrder = "update course_list_local set courseOrder=? where userId=? and coursesetId=? and id=?",
	sql_getPreOrder = "select (courseOrder-1)as pre from course_list_local where userId=? and coursesetId=? and id=?",
	sql_getChangeId = "select id from course_list_local where userId=? and coursesetId=? and courseOrder=?",
	sql_updateDownward = "update course_list_local set courseOrder=courseOrder+1 where userId=? and coursesetId=? and id=?",
	sql_updateUpward = "update course_list_local set courseOrder=courseOrder-1 where userId=? and coursesetId=? and id=?",
	sql_getNextOrder = "select (courseOrder+1) as next from course_list_local where userId=? and coursesetId=? and id=?",
	sql_updateExpCurOrder_sub = "update course_list_local set courseOrder=courseOrder-1 where userId=? and coursesetId=? and courseOrder>?",
	sql_updateCurOrder = "update course_list_local set courseOrder=? where userId=? and coursesetId=? and  id=?",
	sql_updateExpCurOrder_add = "update course_list_local set courseOrder=courseOrder+1 where userId=? and coursesetId=? and courseOrder<?",
	sql_createNewCourseList = "insert into course_list_local(userId,coursesetId,courseOrder) values (?,?,?)",
	sql_updateNewCoursesetOrder = "update course_list_local set coursesetId=?,courseOrder=? where userId=? and id=?",
	sql_saveCourseList = "update course_list_local set courseName=?,lastUpdateTime=? where userId=? and coursesetId=? and id=?",
	sql_courseNameSave = "update course_list_local set courseName=? where userId=? and coursesetId=? and id=?",
	sql_sectionNameSave = "update course_local set sectionName=? where userId=? and coursesetId=? and courseId=? and titleType=? and sectionNum=?",
	sql_updateCourseUpdateTime = "update course_list_local set lastUpdateTime=? where userId=? and coursesetId=? and id=?",
	sql_getCourseSections = "select * from course_local where userId = ? and coursesetId = ? and courseId = ? order by sectionNum ",
	sql_getCourseListByUid = "SELECT `id`,`courseName`,UNIX_TIMESTAMP(`lastUpdateTime`) as lastUpdateTime FROM `course_list_local` where userId=? and  coursesetId=? order by courseOrder",
	sql_getCourseList = "select * from course_list_local where coursesetId=? order by courseOrder",
	sql_getCourseNameAndOrder = "select *  from course_list_local where userId=? and coursesetId=? and id=? order by courseOrder",
	sql_removeCourseSections = "DELETE FROM `course_local` WHERE  userId=? and coursesetId=? and courseId=?",
	sql_updateCoursesetContent = "update course_local set coursesetId=? where userId=? and courseId=?",
	sql_removeCourseList = "DELETE FROM `course_list_local` WHERE  userId=? and coursesetId=? and id=?",
	sql_updateMoveOrder = "update course_list_local set courseOrder=courseOrder-1 where userId=? and coursesetId=? and courseOrder>?",
	sql_createSection = 'INSERT INTO course_local(userId,coursesetId,courseId,titleType,sectionNum,sectionName,sectionContent)VALUES(?,?,?,?,?,?,?)',
	sql_saveSection = "UPDATE `course_local` SET `sectionName`=?,`sectionContent`=? WHERE `userId` = ? and coursesetId=? and courseId=? and titleType=? and sectionNum=?",
	sql_sectionContentVerify = "select md5(sectionContent) as sectionMD5 from course_local where  userId=? and coursesetId=? and courseId=? and sectionNum=? and titleType=?",
	sql_updateSection = "update course_local set sectionNum=sectionNum-1 where userId=? and coursesetId=? and courseId=? and titleType=? and sectionNum>=?", //删除章节后在更新章节
	sql_updateSectionNum = "update course_local set sectionNum=sectionNum+1 where userId=? and coursesetId=? and courseId=? and titleType=? and sectionNum>=?", //添加章节后在更新章节
	sql_removeSection = "delete from course_local where userId=? and coursesetId=? and courseId=? and titleType=? and sectionNum=?  ",
	sql_getReleaseCoursesetAll = "select * from course_release where coursesetId=? and titleType=0",
	sql_getCoursesetAll = "select * from course_local where coursesetId=? and titleType=0",
	sql_getSuccessCoursesetAll = "select * from course_success where   coursesetId=? and titleType=0",
	sql_viewReleaseCourseSectionById = "select * from course_release where coursesetId=? and courseId=? order by sectionNum", //查看待审核成功
	sql_getReleaseCourseListById = "select * from course_list_release where coursesetId=? and courseId=? order by courseOrder",
	sql_viewReleaseCoursesetList_juhe = "select * from course_list_release where coursesetId=? order by courseOrder",
	sql_viewSuccessCourseSectionById_juhe = "select * from course_success where  coursesetId=? and courseId=? order by sectionNum", //查看审核成功
	sql_viewSuccessCoursesetList_juhe = "select * from course_list_success  where  coursesetId=? order by courseOrder",
	sql_viewSunccessFreeCourse = "select *  from course_list_success where  coursesetId=? and feeFlag=0 order by courseOrder",
	sql_getSuccessCourseListById = "select * from course_list_success where coursesetId=? and courseId=? order by courseOrder",
	sql_purchaseSuccess = "INSERT INTO course_buyRecord(userId,coursesetId)VALUES(?,?)",
	sql_getPurchasedCourse = "select count(coursesetId) as count from course_buyRecord where userId=? and coursesetId=? ",
	sql_approvalCourseset_insert = "insert into courseset_success(coursesetId,userId,coursesetName,courseType) select coursesetId,userId,coursesetName,courseType from courseset_release where  coursesetId=? ",
	sql_approvalCourse_insert = "insert into course_list_success(userId,coursesetId,courseId,courseName,courseOrder,feeFlag) select userId,coursesetId,courseId,courseName,courseOrder,feeFlag from course_list_release where  coursesetId=? order by courseOrder",
	sql_approvalCourseSections_insert = "insert into course_success(id,userId,coursesetId,courseId,titleType,sectionNum,sectionName,sectionContent) select id, userId,coursesetId,courseId,titleType,sectionNum,sectionName,sectionContent from course_release where  coursesetId=?",
	sql_approvalCourseset_del = "delete from courseset_success where coursesetId=?",
	sql_approvalCourse_del = "delete from course_list_success where coursesetId=?",
	sql_approvalCourseSections_del = "delete from course_success where coursesetId=?",
	sql_course_list_release_insert = "insert into course_list_release(userId,coursesetId,courseId,courseName,courseOrder) select userId,coursesetId,id as courseId,courseName,courseOrder from course_list_local where userId=? and coursesetId=? order by courseOrder",
	sql_course_release_insert = "insert into course_release(id,userId,coursesetId,courseId,titleType,sectionNum,sectionName,sectionContent) select id, userId,coursesetId,courseId,titleType,sectionNum,sectionName,sectionContent from course_local where userId=? and coursesetId=? ",
	sql_courseTocourseset_release_insert = "insert into courseset_release(coursesetId,userId,coursesetName) select id as coursesetId,userId,coursesetName from courseset_local where userId=? and id=?",
	sql_successTocourseset_release_insert = "insert into courseset_release(coursesetId,userId,coursesetName,courseType) select coursesetId,userId,coursesetName,courseType from courseset_success  where  coursesetId=?",
	sql_successToReleaseList_insert = "insert into course_list_release(userId,coursesetId,courseId,courseName,courseOrder,feeFlag) select userId,coursesetId,courseId,courseName,courseOrder,feeFlag from course_list_success where  coursesetId=? order by courseOrder",
	sql_successToReleaseContent_insert = "insert into course_release(id,userId,coursesetId,courseId,titleType,sectionNum,sectionName,sectionContent) select id,userId,coursesetId,courseId,titleType,sectionNum,sectionName,sectionContent from course_success where coursesetId=? ",
	sql_updateReleaseCourseFeeFlag = "update courseset_release set courseType=? where userId=? and coursesetId=?",
	sql_updateReleaseCourseListFree = "update course_list_release set feeFlag=0 where userId=? and coursesetId=? ",
	sql_updateReleaseCourseListFee = "update course_list_release set feeFlag=1 where userId=? and coursesetId=?",
	sql_removeReleaseCourseset = "DELETE FROM `courseset_release` WHERE userId=? and coursesetId=?  ",
	sql_removeReleaseCourseListById = "DELETE FROM `course_list_release` WHERE userId=? and coursesetId=?  ",
	sql_removeReleaseCourseSectionsById = "DELETE FROM `course_release` WHERE userId=? and coursesetId=?",
	sql_removeReleaseCoursesetByCid = "DELETE FROM `courseset_release` WHERE  coursesetId=?  ",
	sql_removeReleaseCourseByCid = "DELETE FROM `course_list_release` WHERE   coursesetId=?",
	sql_removeReleaseCourseSectionsByCid = "DELETE FROM `course_release` WHERE  coursesetId=?",
	sql_canclePurchasedCourse = "delete from course_buyRecord where userId=? and coursesetId=?",
	sql_getUnpublishCourseCount = "select count(*) as count from courseset_local where userId=? and publishedFlag=0",
	sql_getUnpublishedCourseListByUid = "select id,coursesetName from courseset_local where userId=? and  publishedFlag=0 order by lastUpdateTime desc limit ?,?",
	sql_updateCouseListPublishFlag = "update courseset_local set publishedFlag=? where  id=?",
	sql_unPublishSucessCourse = "update `courseset_success` set isShow=0 where userId=? and coursesetId=?";
//============================================================================//

//创建课程目录
const createCourseset = (userId, cb) => {
	var ret;
	userService.getUserPermission(userId, (permission) => {
		if (permission.indexOf("DEPLOY_COURSE") > -1 || permission.indexOf("OFFLINE_COURSE") > -1 || permission.indexOf("DISPARK_COURSE") > -1) {
			var createTime = moment().format('YYYY-MM-DD HH:mm:ss');
			var lastUpdateTime = createTime;
			var args = [userId, createTime, lastUpdateTime];
			pool.query(sql_createCoursesetList, args, (err, result) => {
				if (err) {
					console.error(err);
					ret = {
						result: -1,
						msg: "创建失败"
					};
					cb(ret);
				} else {
					var coursesetId = result.insertId;
					ret = {
						result: 0,
						coursesetId: coursesetId,
						createTime: createTime

					};
					cb(ret);
				}
			});
		} else {
			ret = {
				result: -1,
				msg: "没有权限"
			};
			cb(ret);
		}
	});
}

//获取课程目录列表
const getCoursesetList = (userId, cb) => {
	var ret, args = [userId];
	pool.query(sql_getCoursesetList, args, (err, rows) => {
		if (err) {
			console.error(err);
			ret = {
				result: -1,
				msg: "获取课程目录列表失败"
			};
		} else {
			var coursesetInfos = [];
			for (let k in rows) {
				var row = rows[k];
				var coursesetInfo = {
					coursesetId: row.id,
					coursesetName: row.coursesetName,
					createTime: row.createTime,
					lastUpdateTime: row.lastUpdateTime,
					publishedFlag: row.publishedFlag
				};
				coursesetInfos.push(coursesetInfo);
			}
			ret = {
				result: 0,
				coursesetInfos: coursesetInfos
			};
		}
		cb(ret);
	});

}

//更新课程目录名字
const coursesetNameSave = (userId, coursesetInfo, cb) => {
	var coursesetId = coursesetInfo.coursesetId,
		coursesetName = coursesetInfo.coursesetName,
		lastUpdateTime = moment().format('YYYY-MM-DD HH:mm:ss'),
		args = [coursesetName, lastUpdateTime, userId, coursesetId];
	pool.query(sql_coursesetNameSave, args, (err) => {
		if (err) {
			console.error(err);
			ret = {
				result: -1,
				msg: "保存失败"
			};
			cb(ret);
		} else {
			ret = {
				result: 0,
				lastUpdateTime: lastUpdateTime
			};
			cb(ret);
		}

	});
}

//删除课程目录
const delCourseset = (userId, coursesetId, cb) => {
	var ret,
		args = [userId, coursesetId];
	pool.query(sql_delCourseset, args, (err) => {
		if (err) {
			console.error(err);
			ret = {
				result: -1,
				msg: "删除失败"
			};
			cb(ret);
		} else {
			pool.query(sql_delCoursesetList, args, (err) => {
				if (err) {
					console.error(err);
					ret = {
						result: -1,
						msg: "删除失败"
					};
					cb(ret);
				} else {
					pool.query(sql_delCoursesetSection, args, (err) => {
						if (err) {
							console.error(err);
							ret = {
								result: -1,
								msg: "删除失败"
							};
							cb(ret);
						} else {
							ret = {
								result: 0,
								msg: "删除成功"
							};
							cb(ret);
						}

					});
				}

			});
		}
	});
}

//获取课程名称和排列的序号
const getCourseNameAndOrder = (userId, coursesetId, courseId, cb) => {
	var ret, args = [userId, coursesetId, courseId];
	pool.query(sql_getCourseNameAndOrder, args, (err, rows) => {
		if (err) {
			console.error(err);
			ret = {
				result: -1,
				msg: "获取失败"
			}
		} else {
			ret = {
				result: 0,
				courseName: rows[0].courseName,
				courseOrder: rows[0].courseOrder
			}
		}
		cb(ret);
	});
}

//获取课程的总数量
const getOrderNum = (userId, coursesetId, cb) => {
	var ret, args = [userId, coursesetId];
	pool.query(sql_getOrderNum, args, (err, rows) => {
		if (err) {
			console.error(err);
			ret = {
				result: -1,
				msg: "获取失败"
			}
		} else {
			ret = {
				result: 0,
				orderNum: rows[0].orderNum
			}
		}
		cb(ret);
	});
}

//将课程章节移动到相应的课程目录下
const moveToCourseset = (userId, coursesetInfo, cb) => {
	var courseId = coursesetInfo.courseId,
		oldCoursesetId = coursesetInfo.oldCoursesetId,
		newCoursesetId = coursesetInfo.newCoursesetId,
		ret, args;
	getCourseNameAndOrder(userId, oldCoursesetId, courseId, (list) => {
		var courseOrder = list.courseOrder;
		args = [userId, oldCoursesetId, courseOrder];
		pool.query(sql_updateExpCurOrder_sub, args, (err) => {
			if (err) {
				console.error(err);
				ret = {
					result: -1,
					msg: "移动失败"
				}
				cb(ret);
			} else {
				getOrderNum(userId, newCoursesetId, (count) => {
					var newOrder = parseInt(count.orderNum) + 1;
					args = [newCoursesetId, newOrder, userId, courseId];
					pool.query(sql_updateNewCoursesetOrder, args, (err) => {
						if (err) {
							console.error(err);
							ret = {
								result: -1,
								msg: "移动失败"
							}
							cb(ret);
						} else {
							args = [newCoursesetId, userId, courseId];
							pool.query(sql_updateCoursesetContent, args, (err) => {
								if (err) {
									console.error(err);
									ret = {
										result: -1,
										msg: "移动失败"
									}
									cb(ret);
								} else {
									ret = {
										result: 0,
										msg: "移动成功"
									}
									cb(ret);
								}
							});
						}
					});

				});
			}
		});
	});
}

//移动排序(0是上移，1是下移，2是置顶，3是置底)
const changeOrder = (userId, coursesetInfo, cb) => {
	var ret,
		coursesetId = coursesetInfo.coursesetId,
		courseId = coursesetInfo.courseId,
		orderType = coursesetInfo.orderType;
	if (orderType == 0) { //上移操作
		var args = [userId, coursesetId, courseId];
		pool.query(sql_getCourseNameAndOrder, args, (err, rows2) => {
			if (err) {
				console.error(err);
				ret = {
					result: -1,
					msg: "移动失败"
				};
				cb(ret);
			} else if (rows2[0].courseOrder == 1) {
				ret = {
					result: 1,
					msg: "无法上移"
				};
				cb(ret);
			} else {
				pool.query(sql_getPreOrder, args, (err, rows) => {
					if (err) {
						console.error(err);
						ret = {
							result: -1,
							msg: "移动失败"
						};
						cb(ret);
					} else {
						var courseOrder = rows[0].pre;
						var args1 = [userId, coursesetId, courseOrder];
						pool.query(sql_getChangeId, args1, (err, rows1) => {
							if (err) {
								console.error(err);
								ret = {
									result: -1,
									msg: "移动失败"
								};
								cb(ret);
							} else {
								var courseId = rows1[0].id;
								var args2 = [userId, coursesetId, courseId];
								pool.query(sql_updateDownward, args2, (err) => {
									if (err) {
										console.error(err);
										ret = {
											result: -1,
											msg: "移动失败"
										};
										cb(ret);
									} else {
										pool.query(sql_updateUpward, args, (err) => {
											if (err) {
												console.error(err);
												ret = {
													result: -1,
													msg: "移动失败"
												};
												cb(ret);
											} else {
												ret = {
													result: 0,
													msg: "移动成功"
												};
												cb(ret);
											}
										});
									}
								})
							}
						});
					}
				});
			}
		});
	} else if (orderType == 1) { //下移操作
		var args = [userId, coursesetId, courseId];
		pool.query(sql_getCourseNameAndOrder, args, (err, rows2) => {
			if (err) {
				console.error(err);
				ret = {
					result: -1,
					msg: "移动失败"
				};
				cb(ret);
			} else {
				var args2 = [userId, coursesetId];
				pool.query(sql_getOrderNum, args2, (err, rows3) => {
					if (err) {
						console.error(err);
						ret = {
							result: -1,
							msg: "移动失败"
						};
						cb(ret);
					} else {
						if (rows2[0].courseOrder == rows3[0].orderNum) {
							ret = {
								result: 2,
								msg: "无法下移"
							};
							cb(ret);
						} else {
							pool.query(sql_getNextOrder, args, (err, rows) => {
								if (err) {
									console.error(err);
									ret = {
										result: -1,
										msg: "移动失败"
									};
									cb(ret);
								} else {
									var courseOrder = rows[0].next;
									var args1 = [userId, coursesetId, courseOrder];
									pool.query(sql_getChangeId, args1, (err, rows1) => {
										if (err) {
											console.error(err);
											ret = {
												result: -1,
												msg: "移动失败"
											};
											cb(ret);
										} else {
											var courseId = rows1[0].id;
											var args2 = [userId, coursesetId, courseId];
											pool.query(sql_updateUpward, args2, (err) => {
												if (err) {
													console.error(err);
													ret = {
														result: -1,
														msg: "移动失败"
													};
													cb(ret);
												} else {
													pool.query(sql_updateDownward, args, (err) => {
														if (err) {
															console.error(err);
															ret = {
																result: -1,
																msg: "移动失败"
															};
															cb(ret);
														} else {
															ret = {
																result: 0,
																msg: "移动成功"
															};
															cb(ret);
														}
													});
												}
											})
										}
									});
								}
							});
						}
					}
				});
			}
		});

	} else if (orderType == 2) { //置顶操作
		var args = [userId, coursesetId, courseId];
		pool.query(sql_getCourseNameAndOrder, args, (err, rows) => {
			if (err) {
				console.error(err);
				ret = {
					result: -1,
					msg: "移动失败"
				};
				cb(ret);
			} else if (rows[0].courseOrder == 1) {
				ret = {
					result: 1,
					msg: "已经置顶,无法上移"
				};
				cb(ret);
			} else {
				var courseOrder = rows[0].courseOrder;
				var args1 = [userId, coursesetId, courseOrder];
				pool.query(sql_updateExpCurOrder_add, args1, (err) => {
					if (err) {
						ret = {
							result: -1,
							msg: "移动失败"
						};
						cb(ret);
					} else {
						var courseOrder = 1;
						var args2 = [courseOrder, userId, coursesetId, courseId];
						pool.query(sql_updateCurOrder, args2, (err) => {
							if (err) {
								console.error(err);
								ret = {
									result: -1,
									msg: "移动失败"
								};

							} else {
								ret = {
									result: 0,
									msg: "移动成功"
								};
							}
							cb(ret);
						});
					}
				});
			}
		});

	} else { //置底操作
		var args = [userId, coursesetId, courseId];
		pool.query(sql_getCourseNameAndOrder, args, (err, rows2) => {
			if (err) {
				console.error(err);
				ret = {
					result: -1,
					msg: "移动失败"
				};
				cb(ret);
			} else {
				var args2 = [userId, coursesetId];
				pool.query(sql_getOrderNum, args2, (err, rows3) => {
					if (err) {
						console.error(err);
						ret = {
							result: -1,
							msg: "移动失败"
						};
						cb(ret);
					} else {
						if (rows2[0].courseOrder == rows3[0].orderNum) {
							ret = {
								result: 2,
								msg: "已经置底,无法下移"
							};
							cb(ret);
						} else {
							pool.query(sql_getCourseNameAndOrder, args, (err, rows) => {
								if (err) {
									ret = {
										result: -1,
										msg: "移动失败"
									};
									cb(ret);
								} else {
									var courseOrder = rows[0].courseOrder;
									var args1 = [userId, coursesetId, courseOrder];
									pool.query(sql_updateExpCurOrder_sub, args1, (err) => {
										if (err) {
											ret = {
												result: -1,
												msg: "移动失败"
											};
											cb(ret);
										} else {
											pool.query(sql_getOrderNum, [userId, coursesetId], (err, rows1) => {
												if (err) {
													console.error(err);
													ret = {
														result: -1,
														msg: "移动失败"
													};
													cb(ret);
												} else {
													var courseOrder = rows1[0].orderNum;
													var args2 = [courseOrder, userId, coursesetId, courseId];
													pool.query(sql_updateCurOrder, args2, (err) => {
														if (err) {
															console.error(err);
															ret = {
																result: -1,
																msg: "error"
															};
															cb(ret);
														} else {

															ret = {
																result: 0,
																msg: "移动成功"
															};
															cb(ret);

														}
													});
												}
											});

										}
									});
								}
							});
						}
					}
				});
			}
		});
	}
}

//创建课程
const createCourse = (userId, coursesetId, cb) => {
	var ret, args = [userId, coursesetId];
	pool.query(sql_createCourseList, args, (err, result) => {
		if (err) {
			console.error(err);
			ret = {
				result: -1,
				msg: "创建失败"
			};
			cb(ret);
		} else {
			getOrderNum(userId, coursesetId, (count) => {
				var courseId = result.insertId;
				var orderNum = count.orderNum;
				args = [orderNum, userId, coursesetId, courseId];
				pool.query(sql_updateOrder, args, (err) => {
					if (err) {
						console.error(err);
						ret = {
							result: -1,
							msg: "创建失败"
						};
						cb(ret);

					} else {
						var sectionInfo = {
							courseId: courseId,
							coursesetId: coursesetId,
							titleType: 0,
							sectionNum: 0,
							sectionName: "无标题小节"
						};
						createSection(userId, sectionInfo, (ret) => {
							if (ret.result === 0) {
								delete sectionInfo.sectionName;
								sectionInfo.titleType = 1;
								createSection(userId, sectionInfo, (ret) => {
									if (ret.result === 0) {
										sectionInfo.titleType = 2;
										createSection(userId, sectionInfo, (ret) => {
											if (ret.result === 0) {
												sectionInfo.titleType = 3;
												createSection(userId, sectionInfo, (ret) => {
													ret = {
														result: 0,
														courseId: courseId
													};
													cb(ret);
												});
											}
										});
									}
								});
							}
						});
					}

				});
			});

		}
	});
}

//删除课程
const removeCourseById = (userId, coursesetId, courseId, cb) => {
	var ret, args = [userId, coursesetId, courseId];
	getCourseNameAndOrder(userId, coursesetId, courseId, (list) => {
		pool.query(sql_removeCourseList, args, (err) => {
			if (err) {
				console.error(err);
				ret = {
					result: -1,
					msg: "删除失败"
				};
				cb(ret);
			} else {
				pool.query(sql_removeCourseSections, args, (err) => {
					if (err) {
						console.error(err);
						ret = {
							result: -1,
							msg: "删除失败"
						};
						cb(ret);
					} else {
						var courseOrder = list.courseOrder;
						args = [userId, coursesetId, courseOrder];
						pool.query(sql_updateMoveOrder, args, (err) => {
							if (err) {
								console.error(err);
								ret = {
									result: -1,
									msg: "删除失败"
								};
								cb(ret);
							} else {
								ret = {
									result: 0,
									msg: "删除成功"
								};
								cb(ret);
							}
						});

					}
				});
			}
		});
	});
};

//获取课程列表
const viewCourseList = (userInfo, coursesetId, cb) => {
	var ret;
	if (userInfo) {
		var userId = userInfo.id;
		var args = [userId, coursesetId];
		pool.query(sql_getCourseListByUid, args, (err, rows) => {
			if (err) {
				console.error(err);
				ret = {
					result: -1,
					msg: "获取课程列表失败"
				};
				cb(ret);
			} else {
				getCoursesetContent(coursesetId, (list) => {
					var courseInfos = {
						coursesetName: list.coursesetName,
						courseList: []
					};
					for (let k in rows) {
						var row = rows[k];
						var courseInfo = {
							courseId: row.id,
							courseName: row.courseName,
							lastUpdateTime: row.lastUpdateTime,
						};
						courseInfos.courseList.push(courseInfo);
					}
					ret = {
						result: 0,
						courseInfos: courseInfos
					};
					cb(ret);
				});
			}
		});
	} else {
		ret = {
			result: -1,
			msg: "未登录"
		};
		cb(ret);
	}
};

//查看课程内容
//返回 
//var courseInfo = {
//  "courseName": "愤怒的小鸟",
//  "courseList": [{sectionName: "章节一", sectionContent: "<h1>1111111</h1>"}, {
//      sectionContent: "章二",
//      sectionContent: "222222"
//  }],
//  "learnPoint": "learnPoint",
//  "think": "think",
//  "homeWork": "homeWork"
//};
const viewCourseById = (userInfo, coursesetId, courseId, cb) => {
	var ret;
	if (userInfo) {
		var userId = userInfo.id;
		var args = [userId, coursesetId, courseId];
		getCourseNameAndOrder(userId, coursesetId, courseId, (list) => {
			getCoursesetContent(coursesetId, (rb) => {
				var courseContent = {
					coursesetId: coursesetId,
					coursesetName: rb.coursesetName,
					courseId: courseId,
					courseOrder: list.courseOrder,
					courseName: list.courseName,
					courseList: []
				};
				pool.query(sql_getCourseSections, args, (err, rows) => {
					if (err) {
						ret = {
							result: -1,
							msg: "查看失败"
						};
						cb(ret);
					} else {
						for (var k in rows) {
							var row = rows[k];
							if (row.titleType === 0) {
								var sectionContent = {
									sectionName: row.sectionName,
									sectionContent: row.sectionContent
								};
								courseContent.courseList.push(sectionContent);
							} else if (row.titleType === 1) {
								courseContent.learnPoint = row.sectionContent;
							} else if (row.titleType === 2) {
								courseContent.think = row.sectionContent;
							} else {
								courseContent.homeWork = row.sectionContent;
							}
						}
						ret = {
							result: 0,
							courseContent: courseContent
						};
						cb(ret);
					};
				});
			});
		});
	} else {
		ret = {
			result: -1,
			msg: "未登录"
		};
		cb(ret);
	}
};

//添加章节
//sectionInfo={courseId,titleType,sectionNum,sectionName}titleType,sectionName,sectionContent可能存在
const createSection = (userId, sectionInfo, cb) => {
	var ret, courseId = sectionInfo.courseId,
		coursesetId = sectionInfo.coursesetId,
		titleType = sectionInfo.titleType,
		sectionNum = sectionInfo.sectionNum;
	if (sectionNum) {
		var args = [userId, coursesetId, courseId, titleType, sectionNum];
		pool.query(sql_updateSectionNum, args, (err) => {
			if (err) {
				console.error(err);
				ret = {
					result: -1,
					msg: "添加章节失败"
				};
				cb(ret);
			} else {
				var sectionNum = sectionInfo.sectionNum ? sectionInfo.sectionNum : 0,
					sectionName = sectionInfo.sectionName ? sectionInfo.sectionName : '无标题小节',
					sectionContent = sectionInfo.sectionContent ? sectionInfo.sectionContent : "",
					titleType = sectionInfo.titleType ? sectionInfo.titleType : 0,
					args = [userId, coursesetId, courseId, titleType, sectionNum, sectionName, sectionContent];
				pool.query(sql_createSection, args, (err) => {
					if (err) {
						console.error(err);
						ret = {
							result: -1,
							msg: "添加章节失败"
						};
					} else {
						ret = {
							result: 0,
							msg: "添加章节成功"
						};
					}
					cb(ret);
				});
			}
		});
	} else {
		var sectionName = sectionInfo.sectionName ? sectionInfo.sectionName : '',
			sectionContent = sectionInfo.sectionContent ? sectionInfo.sectionContent : "",
			titleType = sectionInfo.titleType ? sectionInfo.titleType : 0,
			args = [userId, coursesetId, courseId, titleType, sectionNum, sectionName, sectionContent];
		pool.query(sql_createSection, args, (err) => {
			if (err) {
				console.error(err);
				ret = {
					result: -1,
					msg: "添加章节失败"
				};

			} else {
				ret = {
					result: 0,
					msg: "添加章节成功"
				};

			}
			cb(ret);
		});
	}
};

//保存章节
const saveSection = (userId, sectionInfo, cb) => {
	var ret, courseId = sectionInfo.courseId,
		coursesetId = sectionInfo.coursesetId,
		courseName = sectionInfo.courseName,
		lastUpdateTime = moment().format('YYYY-MM-DD HH:mm:ss'),
		titleTyle = sectionInfo.titleType,
		sectionNum = sectionInfo.sectionNum,
		sectionName = sectionInfo.sectionName,
		sectionContent = sectionInfo.sectionContent;
	var args = [courseName, lastUpdateTime, userId, coursesetId, courseId];
	pool.query(sql_saveCourseList, args, (err) => {
		if (err) {
			console.error(err);
			ret = {
				result: -1,
				msg: "保存失败"
			};
			cb(ret);
		} else {
			args = [sectionName, sectionContent, userId, coursesetId, courseId, titleTyle, sectionNum];
			pool.query(sql_saveSection, args, (err, result) => {
				if (err) {
					console.error(err);
					ret = {
						result: -1,
						msg: "保存失败"
					};
					cb(ret);
				} else if (result.affectedRows < 1) { //可能进不来
					createSection(userId, sectionInfo, (ret2) => {
						if (ret2.result === 0) {
							ret = {
								result: 0,
								msg: "保存成功"
							};
						} else {
							ret = {
								result: -1,
								msg: "保存失败"
							};
						}
						cb(ret);
					});
				} else {
					ret = {
						result: 0,
						msg: "保存成功"
					};
					cb(ret);
				}
			});
		}
	});
};

//更新课程的修改时间
const updateCourseUpdateTime = (userId, coursesetId, courseId) => {
	var upTime = moment().format('YYYY-MM-DD HH:mm:ss'),
		args = [upTime, userId, coursesetId, courseId];
	pool.query(sql_updateCourseUpdateTime, args, (err) => {
		if (err) {
			console.error(err);
		}
	});
};

//更新课程名 
const courseNameSave = (userId, courseInfo, cb) => {
	var courseId = courseInfo.courseId,
		courseName = courseInfo.courseName,
		coursesetId = courseInfo.coursesetId,
		args = [courseName, userId, coursesetId, courseId];
	pool.query(sql_courseNameSave, args, (err) => {
		if (err) {
			console.error(err);
		}
	});
	ret = {
		result: 0,
		msg: "保存成功"
	};

	cb(ret);

}

//更新章节名
const sectionNameSave = (userId, sectionInfo, cb) => {
	var courseId = sectionInfo.courseId,
		coursesetId = sectionInfo.coursesetId,
		sectionName = sectionInfo.sectionName,
		titleType = sectionInfo.titleType,
		sectionNum = sectionInfo.sectionNum,
		args = [sectionName, userId, coursesetId, courseId, titleType, sectionNum];
	pool.query(sql_sectionNameSave, args, (err) => {
		if (err) {
			console.error(err);
		} else {
			updateCourseUpdateTime(userId, coursesetId, courseId);
		}
	});
	ret = {
		result: 0,
		msg: "保存成功"
	};
	cb(ret);
}

//校验章节内容
const sectionContentVerify = (userId, sectionInfo, cb) => {
	var ret, courseId = sectionInfo.courseId,
		coursesetId = sectionInfo.coursesetId,
		sectionNum = sectionInfo.sectionNum,
		titleType = sectionInfo.titleType,
		sectionContent_md5 = sectionInfo.md5;
	var args = [userId, coursesetId, courseId, sectionNum, titleType];
	pool.query(sql_sectionContentVerify, args, (err, rows) => {
		if (err) {
			console.error(err);
			ret = {
				result: -1,
				msg: "校验失败"
			};
			cb(ret);
		} else if (rows.length == 0) {
			ret = {
				result: 1,
				msg: "校验不同"
			};
			cb(ret);
		} else {
			var section_md5 = rows[0].sectionMD5;
			if (section_md5 === sectionContent_md5) {
				ret = {
					result: 0,
					msg: "校验相同"
				};
				cb(ret);
			} else {
				ret = {
					result: 1,
					msg: "校验不同"
				};
				cb(ret);
			}
		}
	});
};

//删除章节
const removeSection = (userId, sectionInfo, cb) => {
	var ret,
		courseId = sectionInfo.courseId,
		coursesetId = sectionInfo.coursesetId,
		titleType = sectionInfo.titleType ? sectionInfo.titleType : 0,
		sectionNum = sectionInfo.sectionNum,
		args = [userId, coursesetId, courseId, titleType, sectionNum];
	pool.query(sql_removeSection, args, (err) => {
		if (err) {
			console.error(err);
			ret = {
				result: -1,
				msg: "删除章节失败"
			};
			cb(ret);
		} else {
			var args = [userId, coursesetId, courseId, titleType, sectionNum];
			pool.query(sql_updateSection, args, (err) => {
				if (err) {
					console.error(err);
					ret = {
						result: -1,
						msg: "删除章节失败"
					};
				} else {
					ret = {
						result: 0,
						msg: "删除章节成功"
					};
				}
				cb(ret);
			});
		}
	});
};

//更新为收费课程
const updateReleaseCourseListFee = (userId, coursesetId) => {
	var args = [userId, coursesetId];
	pool.query(sql_updateReleaseCourseListFee, args, (err) => {
		if (err) {
			console.error(err);
		}
	});
};

//----------------------聚合平台相关方法-------------------------------//
//聚合平台将本地表和通过表中的数据放入到待审核表中(聚合发布课程)
const publishCourse = (userId, rePublishFlag, courseInfo, cb) => {
	var ret,
		coursesetId = courseInfo.coursesetId,
		courseType = courseInfo.courseType,
		args = [userId, coursesetId],
		updateReleaseCourseFee = () => {
			args = [courseType, userId, coursesetId]
			pool.query(sql_updateReleaseCourseFeeFlag, args, (err) => {
				if (err) {
					console.error(err);
					ret = {
						result: -1,
						msg: "发布失败"
					};
					cb(ret);
				} else {
					if (courseType == 0) {
						args = [userId, coursesetId];
						pool.query(sql_updateReleaseCourseListFree, args, (err) => {
							if (err) {
								console.error(err);
								ret = {
									result: -1,
									msg: "发布失败"
								};
								cb(ret);
							} else {
								ret = {
									result: 0,
									msg: "发布成功"
								};
								cb(ret);
							}

						});
					} else {
						updateReleaseCourseListFee(userId, coursesetId);
						var sectionFeeFlag = courseInfo.sectionFeeFlag,
							courseList = [];
						var str = "";
						for (var k in sectionFeeFlag) {
							var courseId = k,
								feeFlag = sectionFeeFlag[k];
							courseList.push(courseId);
							str += " WHEN " + courseId + " THEN " + feeFlag + " ";
						}
						if (courseList.length > 0) {
							var sql_updateCourseReleaseFee = "update course_list_release set feeFlag=CASE courseId  " + str + " END where courseId in (" + courseList + ")";
							pool.query(sql_updateCourseReleaseFee, (err) => {
								if (err) {
									console.error(err);
									ret = {
										result: -1,
										msg: "发布失败"
									};
									cb(ret);
								} else {
									ret = {
										result: 0,
										msg: "发布成功"
									};
									cb(ret);
								}

							});
						} else {
							ret = {
								result: 0,
								msg: "发布成功"
							};
							cb(ret);
						}
					}

				}
			});
		},
		localCourseToRelease = () => {
			args = [userId, coursesetId];
			pool.query(sql_courseTocourseset_release_insert, args, (err) => {
				if (err) {
					console.error(err);
					ret = {
						result: -1,
						msg: "发布失败"
					};
					cb(ret);
				} else {
					pool.query(sql_course_list_release_insert, args, (err) => {
						if (err) {
							console.error(err);
							ret = {
								result: -1,
								msg: "发布失败"
							};
							cb(ret);

						} else {
							pool.query(sql_course_release_insert, args, (err) => {
								if (err) {
									console.error(err);
									ret = {
										result: -1,
										msg: "发布失败"
									};
									cb(ret);

								} else {
									updateReleaseCourseFee();
								}

							});
						}
					});
				}
			});

		},
		successToRelease = () => {
			args = [coursesetId];
			pool.query(sql_successTocourseset_release_insert, args, (err) => {
				if (err) {
					console.error(err);
					ret = {
						result: -1,
						mg: "更新失败"
					}
					cb(ret);
				} else {
					pool.query(sql_successToReleaseList_insert, args, (err) => {
						if (err) {
							console.error(err);
							ret = {
								result: -1,
								mg: "更新失败"
							}
							cb(ret);

						} else {
							pool.query(sql_successToReleaseContent_insert, args, (err) => {
								if (err) {
									console.error(err);
									ret = {
										result: -1,
										mg: "更新失败"
									}
									cb(ret);

								} else {
									updateReleaseCourseFee();
								}
							});
						}
					});
				}
			});

		};
	userService.getUserPermission(userId, (permission) => {
		if (permission.indexOf("DEPLOY_COURSE") > -1 || permission.indexOf("OFFLINE_COURSE") > -1 || permission.indexOf("DISPARK_COURSE") > -1) {
			var args = [userId, coursesetId];
			pool.query(sql_removeReleaseCourseset, args, (err) => {
				if (err) {
					console.error(err);
					ret = {
						result: -1,
						msg: "发布失败"
					};
					cb(ret);
				} else {
					pool.query(sql_removeReleaseCourseListById, args, (err) => {
						if (err) {
							console.error(err);
							ret = {
								result: -1,
								msg: "发布失败"
							};
							cb(ret);
						} else {
							pool.query(sql_removeReleaseCourseSectionsById, args, (err) => {
								if (err) {
									console.error(err);
									ret = {
										result: -1,
										msg: "发布失败"
									};
									cb(ret);
								} else {
									if (rePublishFlag == 0) {
										localCourseToRelease();
									} else {
										successToRelease();
									}

								}
							});
						}

					});
				}
			});

		} else {
			ret = {
				result: -1,
				msg: "没有发布课程权限"
			};
			cb(ret);
		}
	});
};

//聚合平台取消发布课程
const unPublishCourse = (userId, coursesetId, cb) => {
	var args = [userId, coursesetId];
	pool.query(sql_removeReleaseCourseset, args, (err) => {
		if (err) {
			console.error(err);
			ret = {
				result: -1,
				msg: "删除失败"
			};
			cb(ret);
		} else {
			pool.query(sql_removeReleaseCourseListById, args, (err) => {
				if (err) {
					console.error(err);
					ret = {
						result: -1,
						msg: "删除失败"
					};
					cb(ret);
				} else {
					pool.query(sql_removeReleaseCourseSectionsById, args, (err) => {
						if (err) {
							console.error(err);
							ret = {
								result: -1,
								msg: "删除失败"
							};
						} else {
							ret = {
								result: 0,
								msg: "删除成功"
							};
						}
						cb(ret);
					});
				}
			});
		}
	});

};

//聚合平台管理员审批课程     将待审核表的数据插入到审核通过表中(聚合审核课程)
const approvalCourse = (coursesetId, action, cb) => {
	var ret, args = [coursesetId],
		removeReleaseCourse = (coursesetId) => { //删除成功失败都可以 无需回复
			pool.query(sql_removeReleaseCoursesetByCid, args, (err) => {
				if (err) {
					console.error(err);
				} else {
					pool.query(sql_removeReleaseCourseByCid, args, (err) => {
						if (err) {
							console.error(err);
						} else {
							pool.query(sql_removeReleaseCourseSectionsByCid, args, (err) => {
								if (err) {
									console.error(err);
								}
							});
						}
					});
				}
			})
		};

	if (action === "pass") {
		//先删除审核通过表里的数据
		pool.query(sql_approvalCourseset_del, args, (err) => {
			if (err) {
				console.error(err);
				ret = {
					result: -1,
					msg: "审核失败"
				};
				cb(ret);
			} else {
				pool.query(sql_approvalCourse_del, args, (err) => {
					if (err) {
						console.error(err);
						ret = {
							result: -1,
							msg: "审核失败"
						};
						cb(ret);
					} else {
						pool.query(sql_approvalCourseSections_del, args, (err) => {
							if (err) {
								console.error(err);
								ret = {
									result: -1,
									msg: "审核失败"
								};
								cb(ret);
							} else {
								//将待审核表里的数据插入到审核通过表
								pool.query(sql_approvalCourseset_insert, args, (err) => {
									if (err) {
										console.error(err);
										ret = {
											result: -1,
											msg: "审核失败"
										};
										cb(ret);
									} else {
										pool.query(sql_approvalCourse_insert, args, (err) => {
											if (err) {
												console.error(err);
												ret = {
													result: -1,
													msg: "审核失败"
												};
												cb(ret);
											} else {
												pool.query(sql_approvalCourseSections_insert, args, (err) => {
													if (err) {
														console.error(err);
														ret = {
															result: -1,
															msg: "审核失败"
														};
													} else {
														//删除待审核课程数据
														removeReleaseCourse(coursesetId);
														//更改发布标记
														updateCouseListPublishFlag(coursesetId, 1);
														ret = {
															result: 0,
															msg: "审核成功"
														};
													}
													cb(ret);
												});
											}
										});
									}
								});

							}
						});
					}
				});
			}
		});

	} else { //"deny"
		removeReleaseCourse(coursesetId);
		ret = {
			result: 0,
			msg: "审核成功"
		};
		cb(ret);
	}
}

//聚合平台购买整本课程
const purchaseSuccess = (userId, coursesetId, cb) => {
	var ret, args = [userId, coursesetId];
	pool.query(sql_purchaseSuccess, args, (err) => {
		if (err) {
			console.error(err);
			ret = {
				result: -1,
				msg: "购买失败"
			};
		} else {
			ret = {
				result: 0,
				msg: "购买整本书成功"
			};
		}
		cb(ret);
	})
};

//聚合获取本地课程目录下的章节名和小节名
const getCoursesetAll = (coursesetId, cb) => {
	var ret, args = [coursesetId];
	pool.query(sql_getCourseList, args, (err, rows) => {
		if (err) {
			ret = {
				result: -1,
				msg: "查看失败"
			};
			cb(ret);
		} else {
			pool.query(sql_getCoursesetAll, args, (err, rows2) => {
				if (err) {
					console.error(err);
					ret = {
						result: -1,
						msg: "查看失败"
					};
				} else {
					var courseInfo = [];
					for (let i in rows) {
						var courseContent = {
							courseId: rows[i].id,
							courseName: rows[i].courseName,
							teachingPlan: staticPath + "/static/document/",
							courseList: [],
							//							feeFlag: 1
						};
						courseInfo.push(courseContent);
						for (var k in rows2) {
							if (rows[i].id == rows2[k].courseId) {
								courseContent.courseList.push(rows2[k].sectionName);
							}

						}
					}

					ret = {
						result: 0,
						//						courseType: 1, //0是免费课程，1是收费课程，2是线下课程
						courseContent: courseInfo
					};
				}
				cb(ret);
			});
		}
	});
}

//聚合获取待审核的课程目录下的章节名和小节名
const getReleaseCoursesetAll = (coursesetId, cb) => {
	var ret, args = [coursesetId];
	pool.query(sql_viewReleaseCoursesetList_juhe, args, (err, rows) => {
		if (err) {
			ret = {
				result: -1,
				msg: "查看失败"
			};
			cb(ret);
		} else {
			pool.query(sql_getReleaseCoursesetAll, args, (err, rows2) => {
				if (err) {
					console.error(err);
					ret = {
						result: -1,
						msg: "查看失败"
					};
					cb(ret);
				} else {
					getReleaseCoursesetContent(coursesetId, (list) => {
						if (list.courseType == 0) {
							var courseInfo = [];
							for (let i in rows) {
								var courseContent = {
									courseId: rows[i].courseId,
									courseName: rows[i].courseName,
									teachingPlan: staticPath + "/static/document/",
									//									feeFlag: 0,
									courseList: []

								};
								courseInfo.push(courseContent);
								for (var k in rows2) {
									if (rows[i].courseId == rows2[k].courseId) {
										courseContent.courseList.push(rows2[k].sectionName);
									}
								}
							}

							ret = {
								result: 0,
								courseType: 0,
								courseContent: courseInfo
							};
							cb(ret);
						} else {
							var courseInfo = [];
							for (var i in rows) {
								var courseContent = {
									courseId: rows[i].courseId,
									courseName: rows[i].courseName,
									teachingPlan: staticPath + "/static/document/",
									feeFlag: rows[i].feeFlag,
									courseList: []

								};
								courseInfo.push(courseContent);
								for (var k in rows2) {
									if (rows[i].courseId == rows2[k].courseId) {
										courseContent.courseList.push(rows2[k].sectionName);
									}

								}
							}
							ret = {
								result: 0,
								courseType: list.courseType,
								courseContent: courseInfo
							};
							cb(ret);
						}
					});
				}
			});
		}
	});
}

//聚合获取审核通过的课程目录下的章节名和小节名
const getSuccessCoursesetAll = (coursesetId, cb) => {
	var ret, args = [coursesetId];
	pool.query(sql_viewSuccessCoursesetList_juhe, args, (err, rows) => {
		if (err) {
			ret = {
				result: -1,
				msg: "查看失败"
			};
			cb(ret);
		} else {
			pool.query(sql_getSuccessCoursesetAll, args, (err, rows2) => {
				if (err) {
					console.error(err);
					ret = {
						result: -1,
						msg: "查看失败"
					};
					cb(ret);
				} else {
					getSuccessCoursesetContent(coursesetId, (list) => {
						if (list.courseType == 0) {
							var courseInfo = [];
							for (var i in rows) {
								var courseContent = {
									courseId: rows[i].courseId,
									courseName: rows[i].courseName,
									//teachingPlan: staticPath + "/static/document/",//暂时不需要教案
									//									feeFlag: 0,
									courseList: []

								};
								courseInfo.push(courseContent);
								for (var k in rows2) {
									if (rows[i].courseId == rows2[k].courseId) {
										courseContent.courseList.push(rows2[k].sectionName);
									}

								}
							}

							ret = {
								result: 0,
								courseType: 0,
								courseContent: courseInfo
							};
							cb(ret);
						} else {
							var courseInfo = [];
							for (let i in rows) {
								var courseContent = {
									courseId: rows[i].courseId,
									courseName: rows[i].courseName,
									teachingPlan: staticPath + "/static/document/",
									feeFlag: rows[i].feeFlag,
									courseList: []

								};
								courseInfo.push(courseContent);
								for (var k in rows2) {
									if (rows[i].courseId == rows2[k].courseId) {
										courseContent.courseList.push(rows2[k].sectionName);
									}

								}
							}

							ret = {
								result: 0,
								courseType: list.courseType,
								courseContent: courseInfo
							};
							cb(ret);
						}
					});

				}

			});
		}
	});
}

//获取发布者的id
const getReleasePublisherId = (coursesetId, cb) => {
	let ret, args = [coursesetId];
	pool.query(sql_viewReleaseCoursesetList_juhe, args, (err, rows) => {
		if (err) {
			console.error(err);
			ret = {
				result: -1,
				msg: "获取失败"
			}
		} else if (rows.length === 0) {
			ret = {
				result: 1,
				msg: "课程不存在"
			};
		} else {
			ret = {
				result: 0,
				publisherId: rows[0].userId
			}
		}
		cb(ret);
	});
}

//获取审核中的课程集合下对应的课程(供聚合查看侧边栏用)0是管理员权限，自己本身和管理员都可以查看审核中的课程
const viewReleaseCoursesetList = (userInfo, coursesetId, cb) => {
	let ret, args,
		viewReleaseCListPermission = () => {
			args = [coursesetId];
			pool.query(sql_viewReleaseCoursesetList_juhe, args, (err, rows) => {
				if (err) {
					console.error(err);
					ret = {
						result: -1,
						msg: "获取课程列表失败"
					};
					cb(ret);
				} else {
					getReleaseCoursesetContent(coursesetId, (list) => {
						var courseInfos = {
							coursesetName: list.coursesetName,
							courseList: []
						};
						for (let k in rows) {
							var row = rows[k];
							var courseInfo = {
								courseId: row.courseId,
								courseName: row.courseName
							};
							courseInfos.courseList.push(courseInfo);
						}
						ret = {
							result: 0,
							courseInfos: courseInfos
						};
						cb(ret);
					});

				}
			});
		};
	getReleasePublisherId(coursesetId, (rb) => {
		if (userInfo) {
			var userId = userInfo.id;
			var publisherId = rb.publisherId;
			if (publisherId == userId) {
				viewReleaseCListPermission();
			} else {
				userService.getUserPermission(userId, (permission) => {
					if (permission.indexOf("admin") > -1) {
						viewReleaseCListPermission();
					} else {
						ret = {
							result: -1,
							msg: "没有管理员权限"
						};
						cb(ret);
					}
				});
			}
		} else {
			ret = {
				result: -1,
				msg: "未登录"
			};
			cb(ret);
		}
	});
}

//获取审核中的数据(供聚合查看侧边栏用)
const viewReleaseCourseById = (userInfo, coursesetId, courseId, cb) => {
	var ret, args,
		viewReleaseContentPermission = () => {
			args = [coursesetId, courseId];
			pool.query(sql_getReleaseCourseListById, args, (err, rows) => {
				if (err) {
					ret = {
						result: -1,
						msg: "查看失败"
					};
					cb(ret);
				} else if (rows.length === 0) {
					ret = {
						result: 1,
						msg: "课程不存在"
					};
					cb(ret);
				} else {
					pool.query(sql_viewReleaseCourseSectionById, args, (err, rows2) => {
						if (err) {
							console.error(err);
							ret = {
								result: -1,
								msg: "查看失败"
							};
						} else {
							var courseContent = {
								courseId: courseId,
								courseName: rows[0].courseName,
								courseList: []
							};
							for (var k in rows2) {
								var row = rows2[k];
								if (row.titleType === 0) {
									var sectionContent = {
										sectionName: row.sectionName,
										sectionContent: row.sectionContent
									};
									courseContent.courseList.push(sectionContent);
								} else if (row.titleType === 1) {
									courseContent.learnPoint = row.sectionContent;
								} else if (row.titleType === 2) {
									courseContent.think = row.sectionContent;
								} else if (row.titleType === 3) {
									courseContent.homeWork = row.sectionContent;
								}
							}
							ret = {
								result: 0,
								courseContent: courseContent
							};
						}
						cb(ret);
					});
				}
			});
		};
	getReleasePublisherId(coursesetId, (rb) => {
		if (userInfo) {
			var userId = userInfo.id;
			var publisherId = rb.publisherId;
			if (publisherId == userId) {
				viewReleaseContentPermission();
			} else {
				userService.getUserPermission(userId, (permission) => {
					if (permission.indexOf("admin") > -1) {
						viewReleaseContentPermission();
					} else {
						ret = {
							result: -1,
							msg: "没有管理员权限"
						};
						cb(ret);
					}
				});
			}
		} else {
			ret = {
				result: -1,
				msg: "未登录"
			};
			cb(ret);
		}
	});
}

//获得本地课程集合列表的相关信息
const getCoursesetContent = (coursesetId, cb) => {
	var ret, args = [coursesetId];
	pool.query(sql_getCoursesetContent, args, (err, rows) => {
		if (err) {
			console.error(err);
			ret = {
				result: -1,
				msg: "获取失败"
			}
			cb(ret);
		} else if (rows.length === 0) {
			ret = {
				result: 1,
				msg: "课程不存在"
			};
			cb(ret);
		} else {
			ret = {
				result: 0,
				coursesetName: rows[0].coursesetName,
				publishedFlag: rows[0].publishedFlag
			}
			cb(ret);
		}
	});
}

//获得待审核课程集合列表的相关信息
const getReleaseCoursesetContent = (coursesetId, cb) => {
	var ret, args = [coursesetId];
	pool.query(sql_getReleaseCoursesetContent, args, (err, rows) => {
		if (err) {
			console.error(err);
			ret = {
				result: -1,
				msg: "获取失败"
			}
			cb(ret);
		} else if (rows.length === 0) {
			ret = {
				result: 1,
				msg: "课程不存在"
			};
			cb(ret);
		} else {
			ret = {
				result: 0,
				coursesetName: rows[0].coursesetName,
				courseType: rows[0].courseType
			}
			cb(ret);
		}
	});
}

//获取审核通过集合列表的相关信息
const getSuccessCoursesetContent = (coursesetId, cb) => {
	var ret, args = [coursesetId];
	pool.query(sql_getSuccessCoursesetContent, args, (err, rows) => {
		if (err) {
			console.error(err);
			ret = {
				result: -1,
				msg: "获取失败"
			}
			cb(ret);
		} else if (rows.length === 0) {
			ret = {
				result: 1,
				msg: "课程不存在"
			};
			cb(ret);
		} else {
			ret = {
				result: 0,
				coursesetName: rows[0].coursesetName,
				courseType: rows[0].courseType,
				isShow: rows[0].isShow
			}
			cb(ret);
		}
	});
}

//查询审核通过的表中有哪些免费的章节
const viewSunccessFreeCourse = (coursesetId, cb) => {
	var ret, args = [coursesetId];
	pool.query(sql_viewSunccessFreeCourse, args, (err, rows) => {
		if (err) {
			console.error(err);
			ret = {
				result: -1,
				msg: "获取免费章节失败"
			};
			cb(ret);
		} else {
			var courseList = [];
			for (var k in rows) {
				var courseInfo = {
					courseId: rows[k].courseId,
					courseName: rows[k].courseName
				}
				courseList.push(courseInfo);
			}
			ret = {
				result: 0,
				courseList: courseList
			}
			cb(ret);
		}
	});
}

//查看审核通过的课程判断是否为收费的章节
const viewSunccessCourseContent = (coursesetId, courseId, cb) => {
	var ret, args = [coursesetId, courseId];
	pool.query(sql_getSuccessCourseListById, args, (err, rows) => {
		if (err) {
			console.error(err);
			ret = {
				result: -1,
				msg: "获取免费小节失败"
			};
			cb(ret);
		} else if (rows[0].feeFlag == 0) {
			ret = {
				result: 0,
				courseId: rows[0].courseId
			}
			cb(ret);
		} else {
			ret = {
				result: 1,
				courseName: rows[0].courseName,
				courseId: rows[0].courseId
			}
			cb(ret);
		}
	});
}

//获取发布成功的发布者id
const getSuccessPublisherId = (coursesetId, cb) => {
	var ret, args = [coursesetId];
	pool.query(sql_viewSuccessCoursesetList_juhe, args, (err, rows) => {
		if (err) {
			console.error(err);
			ret = {
				result: -1,
				msg: "获取失败"
			}
			cb(ret);
		} else {
			ret = {
				result: 0,
				publisherId: rows[0].userId
			}
			cb(ret);
		}
	});
}

//查看是否购买整本书
const judgePurchasedCourseById = (userId, coursesetId, cb) => {
	var args = [userId, coursesetId];
	pool.query(sql_getPurchasedCourse, args, (err, rows1) => { //查询已购买课程
		if (err) {
			console.error(err);
			cb(false);
		} else {
			cb(rows1[0].count > 0);
		}
	});
};

//从审核通过的表中获取课程目录列表(供聚合查看侧边栏用)
const viewSuccessCoursesetList = (userInfo, coursesetId, cb) => {
	var ret, args,
		viewSuccessCListPermission = (coursePriviliege) => {
			args = [coursesetId];
			pool.query(sql_viewSuccessCoursesetList_juhe, args, (err, rows) => {
				if (err) {
					console.error(err);
					ret = {
						result: -1,
						msg: "获取失败"
					}
					cb(ret);
				} else {
					getSuccessCoursesetContent(coursesetId, (list) => {
						var courseInfos = {
							coursePriviliege: coursePriviliege, //当是免费课程或已经购买的课程（即都能查看的将设置为0）
							coursesetName: list.coursesetName,
							courseType: list.courseType,
							courseList: []
						};
						for (var k in rows) {
							var row = rows[k];
							var courseInfo = {
								courseId: row.courseId,
								courseName: row.courseName,
								feeFlag: row.feeFlag
							};
							courseInfos.courseList.push(courseInfo);
						}
						ret = {
							result: 0,
							courseInfos: courseInfos
						};
						cb(ret);
					});
				}
			});
		};
	getSuccessCoursesetContent(coursesetId, (list) => {
		if (list.isShow === 0) { //该课程已经下架
			ret = {
				result: -1,
				msg: "此课程已经下架"
			};
			cb(ret);
			return;
		}
		if (list.courseType === 3) {//该课程是开放课程，无须在线状态
			viewSuccessCListPermission(0);
		} else if (userInfo) {//先判断用户是否在线
			var userId = userInfo.id;
			if (list.courseType === 0) { //该课程免费
				viewSuccessCListPermission(0);
			} else {
				getSuccessPublisherId(coursesetId, (rb) => {
					if (rb.publisherId == userId) {
						viewSuccessCListPermission(0);
					} else {
						//判断收费课程集合下的免费课程
						viewSunccessFreeCourse(coursesetId, (rb) => {
							if (rb.courseList.length > 0) {
								viewSuccessCListPermission(1);
							} else {
								if (list.courseType === 1) { //若为收费课程，判断是否购买
									judgePurchasedCourseById(userId, coursesetId, (ifBuy) => {
										if (ifBuy) {
											viewSuccessCListPermission(0);
										} else {
											ret = {
												result: 1,
												coursesetId: coursesetId,
												coursesetName: list.coursesetName,
												msg: "此课程为收费课程,请购买学习"
											};
											cb(ret);
										}
									});
								} else if (list.courseType === 2) { //若为线下课程，需判断是否是线下学员
									userService.getUserPermission(userId, (permission) => {
										if (permission.indexOf("OFFLINE_COURSE_STUDY") > -1) {
											viewSuccessCListPermission(0);
										} else {
											ret = {
												result: 2,
												coursesetId: coursesetId,
												coursesetName: list.coursesetName,
												msg: "此课程仅供线下学员学习，请到相关机构购买学习"
											};
											cb(ret);
										}
									});
								}
							}
						});
					}
				});
			}
		} else {
			ret = {
				result: -1,
				msg: "未登录"
			}
			cb(ret);
		}
	});
}

//从审核通过的表中获得的数据(供聚合查看侧边栏用)
const viewSuccessCourseById = (userInfo, coursesetId, courseId, cb) => {
	var ret, args,
		viewSuccessContentPermission = (courseId) => {
			args = [coursesetId, courseId];
			pool.query(sql_getSuccessCourseListById, args, (err, rows) => {
				if (err) {
					console.error(err);
					ret = {
						result: -1,
						msg: "查看失败"
					};
					cb(ret);
				} else {
					pool.query(sql_viewSuccessCourseSectionById_juhe, args, (err, rows2) => {
						if (err) {
							console.error(err);
							ret = {
								result: -1,
								msg: "查看失败"
							};
							cb(ret);
						} else {
							var courseContent = {
								courseId: courseId,
								courseName: rows[0].courseName,
								courseList: []
							};
							for (let k in rows2) {
								var row = rows2[k];
								if (row.titleType === 0) {
									var sectionContent = {
										sectionName: row.sectionName,
										sectionContent: row.sectionContent
									};
									courseContent.courseList.push(sectionContent);
								} else if (row.titleType === 1) {
									courseContent.learnPoint = row.sectionContent;
								} else if (row.titleType === 2) {
									courseContent.think = row.sectionContent;
								} else if (row.titleType === 3) {
									courseContent.homeWork = row.sectionContent;
								}
							}
							ret = {
								result: 0,
								courseContent: courseContent
							};
							cb(ret);

						}
					});
				}

			});

		};
	getSuccessCoursesetContent(coursesetId, (list) => {
		if (list.isShow === 0) { //课程已经下架
			ret = {
				result: -1,
				msg: "此课程已经下架"
			};
			cb(ret);
			return;
		}
		if (list.courseType === 3) { //开放课程,无须判断用户在线
			viewSuccessContentPermission(courseId);
		} else if (userInfo) {//先判断用户是否在线
			var userId = userInfo.id;
			if (list.courseType === 0) { //课程免费	
				viewSuccessContentPermission(courseId);
			} else {
				//判断发布者的id与登录用户是否一致
				getSuccessPublisherId(coursesetId, (rb) => {
					if (rb.publisherId == userId) {
						viewSuccessContentPermission(courseId);
					} else {
						if (list.courseType === 1) { //收费课程判断是否购买
							judgePurchasedCourseById(userId, coursesetId, (ifBuy) => {
								if (ifBuy) { //如果已经购买
									viewSuccessContentPermission(courseId);
									//								console.log("//////" + courseId + "我为收费学员");
								} else {
									//判断收费课程集合下的免费课程
									viewSunccessCourseContent(coursesetId, courseId, (rb) => {
										if (rb.result == 0) {
											var courseId = rb.courseId;
											viewSuccessContentPermission(courseId);
										} else {
											ret = {
												result: 1,
												courseName: rb.courseName,
												coursesetId: coursesetId,
												msg: "此课程为收费课程,请购买学习"
											};
											cb(ret);
										}
									});

								}
							});
						} else { //线下课程判断是否是线下学员
							userService.getUserPermission(userId, (permission) => {
								if (permission.indexOf("OFFLINE_COURSE_STUDY") > -1) {
									viewSuccessContentPermission(courseId);
									//								console.log("//////" + courseId + "我为线下学员");
								} else {
									//判断收费课程集合下的免费课程
									viewSunccessCourseContent(coursesetId, courseId, (rb) => {
										if (rb.result == 0) {
											var courseId = rb.courseId;
											viewSuccessContentPermission(courseId);
										} else {
											ret = {
												result: 2,
												courseName: rb.courseName,
												coursesetId: coursesetId,
												msg: "此课程仅供线下学员学习，请到相关机构购买学习"
											};
											cb(ret);
										}
									});

								}
							});
						}
					}
				});
			}
		} else {
			ret = {
				result: -1,
				msg: "未登录"
			}
			cb(ret);
		}
	});
}

//取消已购买的课程
const canclePurchasedCourse = (userId, coursesetId, cb) => {
	var ret, args = [userId, coursesetId];
	pool.query(sql_canclePurchasedCourse, args, (err) => {
		if (err) {
			ret = {
				result: -1,
				msg: "取消失败"
			};
		} else {
			ret = {
				result: 0,
				msg: "取消成功"
			};
		}
		cb(ret);
	});
};

//未发布课程的数量
const getUnpublishCourseCount = (userId, cb) => {
	var ret, args = [userId];
	pool.query(sql_getUnpublishCourseCount, args, (err, rows) => {
		if (err) {
			console.error(err);
			ret = {
				result: -1,
				msg: "获取失败"
			}
		} else if (rows.length > 0) {
			ret = {
				result: 0,
				courseNum: rows[0].count
			}
		} else {
			ret = {
				result: -1,
				msg: "获取失败"
			}
		}
		cb(ret);
	});
};

//用分页显示未发布课程的列表
const getUnpublishedCourseListByUid = (userId, offset, limit, cb) => {
	var offset = parseInt(offset),
		limit = parseInt(limit);
	getUnpublishCourseCount(userId, (count) => {
		var ret = {
			result: 0,
			courseLimit: count.courseNum,
			courseList: []
		};
		if (count.result === -1) {
			cb(ret);
		} else {
			var args = [userId, offset, limit];
			pool.query(sql_getUnpublishedCourseListByUid, args, (err, rows) => {
				if (err) {
					console.error(err);
					ret = {
						result: -1,
						msg: "获取失败"
					}
				} else {
					var list = [];
					for (let k in rows) {
						var row = rows[k];
						list.push({
							coursesetId: row.id,
							coursesetName: row.coursesetName
						});
					}
					ret.courseList = list
				}
				cb(ret);
			});
		}
	});
};

//更新本地课程发布标记1发布0未发布
const updateCouseListPublishFlag = (coursesetId, publishFlag) => {
	var args = [publishFlag, coursesetId];
	pool.query(sql_updateCouseListPublishFlag, args, (err) => {
		if (err) {
			console.error(err);
		}
	});
}

//聚合平台用户下架已发布的课程
const unPublishSucessCourse = (userId, coursesetId, cb) => {
	var ret, args = [userId, coursesetId];
	pool.query(sql_unPublishSucessCourse, args, (err) => {
		if (err) {
			console.error(err);
			ret = {
				result: -1,
				msg: "下架失败"
			};
		} else {
			ret = {
				result: 0,
				msg: "下架成功"
			};
			updateCouseListPublishFlag(coursesetId, 0);
		}
		cb(ret);
	});

};

//===============================================================================//
module.exports = {
	createCourseset,
	getCoursesetList,
	coursesetNameSave,
	delCourseset,
	moveToCourseset,
	changeOrder,
	createCourse,
	viewCourseById,
	viewCourseList,
	removeCourseById,
	createSection,
	saveSection,
	sectionContentVerify,
	courseNameSave,
	sectionNameSave,
	removeSection,
	getCoursesetAll,
	getReleaseCoursesetAll,
	viewReleaseCoursesetList,
	viewReleaseCourseById,
	getSuccessCoursesetAll,
	viewSuccessCoursesetList,
	viewSuccessCourseById,
	publishCourse,
	unPublishCourse,
	approvalCourse,
	purchaseSuccess,
	canclePurchasedCourse,
	getUnpublishedCourseListByUid,
	unPublishSucessCourse
};
